import { asyncRoutes, constantRoutes } from '@/router'

/**
 * @param routes
 * @param routeName
 */
function getRoute(routes, routeName) {
  for (const item of routes) {
    if (item.name === routeName) return { ...item }
    if (item.children && routeName.indexOf(item.name) > -1) {
      return getRoute(item.children, routeName)
    }
  }
  return null
}

/** *
 * 获取匹配到的路由数组
 */
function getRouteList(routes, menu) {
  const res = []
  menu.forEach((item) => {
    const obj = getRoute(routes, item.path)
    if (obj) {
      obj.meta.title = item.label
      // 分配按钮权限
      if (item.children) {
        const mList = item.children.filter((k) => k.path.indexOf('#') > -1)
        if (mList.length > 0) {
          obj.meta.methods = mList.map((p) => p.path)
        }
      }
      res.push(obj)
    }
  })
  return res
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param menu
 */
export function filterAsyncRoutes(routes, menu) {
  const res = []

  menu.forEach((item) => {
    if (item.path) {
      const obj = getRoute(routes, item.path)
      if (obj) {
        obj.meta.title = item.label
        obj.children = getRouteList(routes, item.children)
        for (const child of item.children) {
          if (child.children) {
            const result = getRouteList(routes, child.children)
            obj.children = [...obj.children, ...result]
          }
        }
        const rdObj = obj.children.find((k) => !k.hidden)
        obj.redirect = obj.path + '/' + rdObj.path
        res.push(obj)
      }
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, menu) {
    return new Promise((resolve) => {
      let accessedRoutes = []
      // 过滤掉第一级
      let menuArr = []
      for (const item of menu) {
        menuArr = menuArr.concat(item.children)
      }
      accessedRoutes = filterAsyncRoutes(asyncRoutes, menuArr)
      // 最后添加404
      accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
      // console.log(accessedRoutes);
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
